package cn.waqwb.controller;

import cn.waqwb.service.UserService;
import cn.waqwb.service.impl.UserServiceImpl;
import cn.waqwb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author JokerQ
 * @date 2020/7/30 - 15:47
 */
//@WebServlet(name = "login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.setCharacterEncoding("UTF-8");
        //1.获取参数
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        System.out.println("email:"+email+",password:"+password);
        //2.验证用户
        UserService userService = new UserServiceImpl();
        User user = userService.getUser(email,password);
        System.out.println(user.toString());
        //3.返回结果
        if(user != null){
            req.getSession().setAttribute("user", user);
            /**
             *  sendRedirect
             *  Calling this method sets the
             *      * status code to {@link #SC_FOUND} 302 (Found).
             *  浏览器对302的响应，默认情况下，使用HTTP协议的GET方法提交请求，
             *  最初请求的内容（比如 POST 参数）也就丢失了。
             *  所以response.sendRedirect()是不能让浏览器来以post方法提交请求的。
             */
            resp.sendRedirect("booklist");
            //req.getRequestDispatcher("booklist").forward(req, resp);
        }else {
            req.setAttribute("errorMsg","用户名或密码错误！");
            resp.sendRedirect("login.jsp");
//            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
